<?php

namespace app\common;

use app\common\model\OperationLog;
use Exception;

class LogService
{
    public static function record(
        string $name,
        int $user_id = 0,
        int $user_type = 1,
        array $content = [],
        string $ip = null,
        string $user_agent = null,
        string $target_id = null,
        int $status = 1
    ) {
        $app =  app('http')->getName();
        $controller = request()->controller();
        $action = request()->action();
        $operation_type = $app . '/' . $controller . '/' . $action;
        try {
            $operation = OperationLog::create([
                'user_id' => $user_id,
                'user_type' => $user_type,
                'app' => $app,
                'operation_type' => $operation_type,
                'operation_name' => $name,
                'request_type' => request()->method(),
                'target_id' => $target_id,
                'ip' => $ip ?: request()->ip(),
                'user_agent' => $user_agent ?: request()->header('User-Agent'),
                'content' => json_encode($content, JSON_UNESCAPED_UNICODE),
                'status' => $status,
                'create_time' => time()
            ]);

            // 异步处理（可选）
            // think-queue 队列任务
            // Queue::push(LogAnalysisJob::class, $operation);

            return $operation;
        } catch (Exception $e) {
            // 紧急日志写入文件
            \think\facade\Log::error('日志记录失败：' . $e->getMessage());
        }
    }
}
